/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.spring.authorizationserver.web;

import com.nimbusds.jose.jwk.RSAKey;
import jakarta.annotation.security.RolesAllowed;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.elsfs.cloud.api.security.key.OAuth2JWKRepository;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * key 管理控制器
 *
 * @author zeng
 */
@RestController
@RequiredArgsConstructor
public class KeyController {
  private final OAuth2JWKRepository oauth2JWKRepository;

  @RolesAllowed("add_jwks")
  @PostMapping("/oauth2/jwks")
  String generate() {
    RSAKey rsaKey = generateKeyPair();
    this.oauth2JWKRepository.save(rsaKey);
    return rsaKey.getKeyID();
  }

  private static RSAKey generateKeyPair() {
    KeyPair keyPair = generateRsaKey();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    return new RSAKey.Builder(publicKey)
        .keyID(UUID.randomUUID().toString())
        .issueTime(new Date())
        .privateKey(privateKey)
        .build();
  }

  private static KeyPair generateRsaKey() {
    KeyPair keyPair;
    try {
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(2048);
      keyPair = keyPairGenerator.generateKeyPair();
    } catch (Exception ex) {
      throw new IllegalStateException(ex);
    }
    return keyPair;
  }
}
